import { computed } from 'vue';
import { mapState, useStore } from 'vuex';

export function useState(mapper) {
    const store = useStore(); // 拿到vuex的store对象
    // const storeStateFns = mapState(["counter", "name", "age", "height"]); // mapState中的数据是需要别人传进来的,这里不能写死
    const storeStateFns = mapState(mapper);

    // 对数据进行转换
    const storeState = {};
    Object.keys(storeStateFns).forEach((fnKey) => {
        const fn = storeStateFns[fnKey].bind({ $store: store }); // $store: store 把上面定义的获取的Vuex中的store绑定到$store上,bind返回一个新的函数,this指向问题

        storeState[fnKey] = computed(fn); // 使用computed 对每个函数进行计算以后赋值给storeState[fnKey],
    });

    return storeState; // 返回整个对象
}
